package org.jeecg.modules.mall.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pdd.pop.sdk.common.util.StringUtils;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.MessageConstant;
import org.jeecg.common.constant.RedisConstant;
import org.jeecg.common.exception.ValidException;
import org.jeecg.common.i18n.Language;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.token.MobileCodeToken;
import org.jeecg.common.util.DySmsHelper;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.common.util.app.CommonUtil;
import org.jeecg.modules.appuser.constant.PayTypeConstant;
import org.jeecg.modules.appuser.constant.TaskNamesConstant;
import org.jeecg.modules.appuser.entity.*;
import org.jeecg.modules.appuser.service.*;
import org.jeecg.modules.jd.entity.JD_position;
import org.jeecg.modules.jd.service.IJD_positionService;
import org.jeecg.modules.mall.entity.InviteBean;
import org.jeecg.modules.mall.entity.TbMnAdzone;
import org.jeecg.modules.mall.entity.TbMnUser;
import org.jeecg.modules.mall.mapper.TbMnUserMapper;
import org.jeecg.modules.mall.service.ITbMnAdzoneService;
import org.jeecg.modules.mall.service.ITbMnUserService;
import org.jeecg.modules.pdd.entity.PddPromotion;
import org.jeecg.modules.pdd.service.IPddPromotionService;
import org.jeecg.modules.system.service.ISysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.util.*;

import static cn.hutool.core.util.RandomUtil.getRandom;
import static org.jeecg.modules.mall.service.impl.Contents.appkey;

/**
 * @Description: app用户
 * @Author: jeecg-boot
 * @Date: 2020-05-12
 * @Version: V1.0
 */
@Slf4j
@Service
public class TbMnUserServiceImpl extends ServiceImpl<TbMnUserMapper, TbMnUser> implements ITbMnUserService {

    @Autowired
    private IJD_positionService jD_positionService;

    @Autowired
    private ITbUserLuckdrawDetailService tbUserLuckdrawDetailService;

    @Autowired
    private ITbUserGameUserShandwService tbUserGameUserShandwService;
    @Autowired
    private ITbMnAdzoneService tbMnAdzoneService;

    @Autowired
    private ITbUserWalletService tbUserWalletService;

    @Autowired
    private ITbUserCashService tbUserCashService;

    @Autowired
    @Lazy(true)
    private ITbUserGameBuidingService tbUserGameBuidingService;


    @Autowired
    private ITbUserIntegralService tbUserIntegralService;
    @Autowired
    private ITbUserIntegralDetailService tbUserIntegralDetailService;

    @Autowired
    @Lazy(true)
    private ITbUserIntegralConfigService tbUserIntegralConfigService;

    @Autowired
    private ITbUserWalletDetailService tbUserWalletDetailService;

    @Autowired
    private ITbUserIntegralConfigDetailService tbUserIntegralConfigDetailService;

    @Autowired
    private ITbUserVipService tbUserVipService;

    @Autowired
    private ITbUserSqtDetailService tbUserSqtDetailService;

    @Autowired
    @Lazy(true)
    private IPddPromotionService pddPromotionService;

    @Autowired
    private ISysDictService sysDictService;


    String sysPassword = "888888";//tbMnUser.getPwd();
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ITbUserSqtService tbUserSqtService;

    @Autowired
    private ITbUserLuckdrawService tbUserLuckdrawService;

    @Autowired
    private ITb_user_contribution_detailService tb_user_contribution_detailService;

    @Autowired
    private ITb_user_contributionService tb_user_contributionService;

    public Result<?> sendSms(String phone) {

        List<DictModel> dictModelList = sysDictService.queryDictItemsByCode("SMS_666666_STATUS");
        String sms_status = dictModelList.get(0).getValue();
        //随机数
        String captcha = RandomUtil.randomNumbers(6);
        if (sms_status.trim().equals("1")) {
            captcha = "666666";
        } else {
            DySmsHelper.smsCode(phone, captcha);
        }
        log.info(">>>>>>>>>>>>>>>>> 验证码 >>>>>>>>>>>>>>>>>>" + captcha);
        String encryptCode = CommonUtil.encryptData(captcha, phone);
        redisUtil.set(RedisConstant.getLoginCodeKey(phone), encryptCode, RedisConstant.CODE_EXPIRE_TIME);
        return Result.ok(Language.L(MessageConstant.SEND_CODE_SUCCESS));
    }


    @Override
    public Result<?> setLoginPwd(String phone, String password) {
        TbMnUser tbMnUser = getUserByPhone(phone);
        String salt = CommonUtil.getSalt();
        String encryptPwd = CommonUtil.getEncryptionPwd(salt, password);
        tbMnUser.setPwd(encryptPwd);
        tbMnUser.setPwdSalt(salt);
        boolean updSuccess = updateById(tbMnUser);

        return Result.error();
    }

    @Override
    public Result<?> login(String phone, String password) {


        return Result.ok("暂未开发");
    }

    public Result<?> loginByInviteCode(String phone, String inviteCode) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            log.info("inviteCode----------------->" + inviteCode);
            if (StringUtils.isEmpty(inviteCode)) {
                return Result.error("参数错误! ");
            }
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("invite_code", inviteCode);
            TbMnUser tbMnUser_ed = this.baseMapper.selectOne(queryWrapper);
            if (tbMnUser_ed == null) {
                return Result.error("邀请码不存在! ");
            }
            TbMnUser tbMnUser = getUserByPhone(phone);
            //校验用户名是否可用
            tbMnUser = getTbMnUser(phone, inviteCode, tbMnUser);
            if (null == tbMnUser) {
                return Result.error("没有推广位，联系管理员! ");
            }
            return userInfo(tbMnUser);
        } catch (ValidException e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }


    private TbMnUser getTbMnUser(String phone, String inviteCode, TbMnUser tbMnUser) {
        if (tbMnUser == null) {
            tbMnUser = new TbMnUser();
            synchronized (tbMnUser) {
                tbMnUser.setAccount(phone);
                tbMnUser.setPwd("");
                QueryWrapper adzoneQueryWrapper = new QueryWrapper();
                //这里改成  只有邀请码
                adzoneQueryWrapper.eq("state", "1");
                List<TbMnAdzone> tbMnAdzoneList = tbMnAdzoneService.list(adzoneQueryWrapper);
                if (null == tbMnAdzoneList && tbMnAdzoneList.size() == 0) {
                    return null;
                }
                TbMnAdzone tbMnAdzone = tbMnAdzoneList.get(0);
                tbMnUser.setAgencyId(tbMnAdzone.getAdzoneId());
                tbMnUser.setState("1");
                tbMnUser.setCreatedAt(new Date());
                tbMnUser.setUserName(phone);
                tbMnUser.setPhone(phone);
                tbMnUser.setOwnRate("62");//默认佣金比率60%
                tbMnUser.setTeamRate("10");
                tbMnUser.setIsReadGuide(0);
                tbMnUser.setFirstLuckdrawStatus(0);
                tbMnUser.setAvater("http://mall.blockinsight.com.cn/icon/logo.svg");
                tbMnUser.setInviteCode(RandomUtil.randomNumbers(6));
                tbMnUser.setIsFirstBuilding(0);
                tbMnUser.setIsGive100(0);
                tbMnUser.setIsRewardSqt(0);
                tbMnUser.setIntegralAgent(0);
                tbMnUser.setHasPayPwd(0);
                QueryWrapper uservipQueryWrapper = new QueryWrapper();
                uservipQueryWrapper.eq("sort", 1);
                TbUserVip tbUserVip = tbUserVipService.getOne(uservipQueryWrapper);
                tbMnUser.setVipId(tbUserVip.getId());
                tbMnUser.setVipName(tbUserVip.getVipName());
                tbMnUser.setRegisterCode(inviteCode);
                if (save(tbMnUser)) {
                    adzoneQueryWrapper.eq("adzone_id", tbMnAdzone.getAdzoneId());
                    tbMnAdzone.setState("2");
                    tbMnAdzone.setAccount(tbMnUser.getId());
                    tbMnAdzoneService.update(tbMnAdzone, adzoneQueryWrapper);
                    //保存sqt
                    if (saveTb_user_contributionService(tbMnUser)) {
                        if (saveUserSqt(tbMnUser)) {
                            if (saveUserWallet(tbMnUser)) {
                                //初始化积分任务
                                if (saveInitIntegralConfigTask(tbMnUser)) {  //去掉自动盖楼
                                    if (saveUserIntegral(tbMnUser)) {
                                        if (savePddPromotion(tbMnUser)) {
                                            if (saveJDPidData(tbMnUser)) {
                                                //增加 邀请人的任务完成情况
                                                String registerCode = tbMnUser.getRegisterCode();
                                                QueryWrapper queryWrapper1 = new QueryWrapper();
                                                queryWrapper1.eq("invite_code", registerCode);
                                                TbMnUser inviteTbMnuser = this.getOne(queryWrapper1);
                                                tbUserIntegralService.doActionTask(inviteTbMnuser.getId(), TaskNamesConstant.Task_INVITE);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return tbMnUser;

    }

    private boolean saveTb_user_contributionService(TbMnUser tbMnUser) {
        Tb_user_contribution tb_user_contribution = new Tb_user_contribution();
        tb_user_contribution.setContributionValue(0);
        tb_user_contribution.setUserId(tbMnUser.getId());
        tb_user_contributionService.save(tb_user_contribution);
        return true;
    }

    private boolean saveJDPidData(TbMnUser tbMnUser) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("status", 0);
        List<JD_position> jd_positionList = jD_positionService.list(queryWrapper);
        if (null != jd_positionList && jd_positionList.size() > 0) {
            JD_position jd_position = jd_positionList.get(0);
            jd_position.setUserId(tbMnUser.getId());
            jd_position.setStatus(1);
            jD_positionService.updateById(jd_position);
            return true;
        }
        return false;


    }

    private boolean savePddPromotion(TbMnUser tbMnUser) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("status", 0);
        List<PddPromotion> pddPromotionList = pddPromotionService.list(queryWrapper);
        if (null != pddPromotionList && pddPromotionList.size() > 0) {
            PddPromotion pddPromotion = pddPromotionList.get(0);
            pddPromotion.setUserId(tbMnUser.getId());
            pddPromotion.setStatus(1);
            pddPromotionService.updateById(pddPromotion);
            return true;
        }
        return false;

    }

    private boolean saveInitIntegralConfigTask(TbMnUser tbMnUser) {
        List<TbUserIntegralConfig> tbUserIntegralConfigList = tbUserIntegralConfigService.getInitConfigList();
        if (null != tbUserIntegralConfigList && tbUserIntegralConfigList.size() > 0) {
            for (TbUserIntegralConfig tbUserIntegralConfig : tbUserIntegralConfigList) {
                TbUserIntegralConfigDetail tbUserIntegralConfigDetail = new TbUserIntegralConfigDetail();
                BeanUtil.copyProperties(tbUserIntegralConfig, tbUserIntegralConfigDetail);
                tbUserIntegralConfigDetail.setId(UUIDGenerator.generate());
                Calendar date = Calendar.getInstance();
                date.set(date.get(Calendar.YEAR), date.get(Calendar.MONTH), date.get(Calendar.DATE), 0, 0, 0);
                tbUserIntegralConfigDetail.setCreateTime(date.getTime());
                Calendar date1 = Calendar.getInstance();
                date1.set(date.get(Calendar.YEAR), date.get(Calendar.MONTH), date.get(Calendar.DATE), 23, 59, 59);
                tbUserIntegralConfigDetail.setEndTime(date1.getTime());
                tbUserIntegralConfigDetail.setUserId(tbMnUser.getId());
                tbUserIntegralConfigDetail.setCompleteState(0);
                tbUserIntegralConfigDetailService.save(tbUserIntegralConfigDetail);
            }

        }
        return true;

    }

    private boolean saveUserIntegral(TbMnUser tbMnUser) {
        TbUserIntegral tbUserIntegral = new TbUserIntegral();

        tbUserIntegral.setIntegral(new BigDecimal("0"));
        tbUserIntegral.setState(1);
        tbUserIntegral.setUserId(tbMnUser.getId());
        //  addIntegralDetail(tbMnUser.getId(), tbUserIntegral, tbUserIntegral.getIntegral(), new BigDecimal(50), TaskNamesConstant.Task_FIRST_LOGIN);
        tbUserIntegralService.save(tbUserIntegral);

        return true;
    }


    @Override
    public Result<?> getInvitedData(String userId) {
        Map<String, Object> resultMap = new HashMap<>();
        QueryWrapper queryWrapper = new QueryWrapper();
        TbMnUser tbMnUser = getById(userId);
        String inviteCode = tbMnUser.getInviteCode();
        queryWrapper.eq("register_code", inviteCode);
        List<TbMnUser> tbMnUserList = this.baseMapper.selectList(queryWrapper);
        int dirct_invite_number = 0;
        int second_invite_number = 0;
        List<InviteBean> inviteBeanList = new ArrayList<>();
        if (null != tbMnUserList && tbMnUserList.size() > 0) {
            for (TbMnUser mnUser : tbMnUserList) {
                InviteBean inviteBean = new InviteBean();
                QueryWrapper secondQueryWrapper = new QueryWrapper();
                secondQueryWrapper.eq("register_code", mnUser.getInviteCode());
                List<TbMnUser> secondtbMnUserList = this.baseMapper.selectList(secondQueryWrapper);
                int secode_invate_count = 0;
                if (null != secondtbMnUserList && secondtbMnUserList.size() > 0) {
                    secode_invate_count = secondtbMnUserList.size();
                    second_invite_number += secode_invate_count;
                }

                inviteBean.setTeamNum(secode_invate_count);
                QueryWrapper gameQueryWrapper = new QueryWrapper();
                gameQueryWrapper.eq("user_id", userId);
                TbUserGameBuiding tbUserGameBuiding = tbUserGameBuidingService.getOneAndUpgradeConfig(userId);

                if (null != tbUserGameBuiding) {
                    if (tbUserGameBuiding.getBusinessHours() > 0) {
                        inviteBean.setBizStatus("1");
                        inviteBean.setSqtRate(tbUserGameBuiding.getBusinessProportion());

                    } else {
                        inviteBean.setBizStatus("0");
                        inviteBean.setSqtRate(tbUserGameBuiding.getUnbusinessProportion());
                    }
                } else {
                    inviteBean.setSqtRate("0");
                    inviteBean.setBizStatus("0");
                }
                inviteBean.setUserName(mnUser.getUserName());
                inviteBean.setVipName(mnUser.getVipName());
                inviteBean.setUserId(mnUser.getId());
                inviteBean.setIntegralAgent(mnUser.getIntegralAgent());
                inviteBeanList.add(inviteBean);
                dirct_invite_number += 1;
            }
        }
        //直接邀请人数
        resultMap.put("dirct_invite_number", dirct_invite_number);
        resultMap.put("team_num", dirct_invite_number + second_invite_number);
        resultMap.put("invite_data", inviteBeanList);
        return Result.ok(resultMap);
    }

    private void getAbleInivateData2(TbMnUser tbMnUser, Map<String, Object> able_map) {
        int inivate_number = (int) able_map.get("inivate_number");
        BigDecimal profit = (BigDecimal) able_map.get("profit");
        QueryWrapper inVitequeryWrapper = new QueryWrapper();
        String inviteCode = tbMnUser.getInviteCode();
        inVitequeryWrapper.eq("register_code", inviteCode);
        //邀请的人数
        List<TbMnUser> tbMnUserList = this.list(inVitequeryWrapper);

        if (null != tbMnUserList && tbMnUserList.size() > 0) {
            for (TbMnUser mnUser : tbMnUserList) {
                QueryWrapper userWalletQueryWrapper = new QueryWrapper();
                userWalletQueryWrapper.eq("user_id", mnUser.getId());
                userWalletQueryWrapper.eq("pay_from", PayTypeConstant.PAYFORM_REBATE);
                List<TbUserWalletDetail> tbUserWalletDetailList = tbUserWalletDetailService.list(userWalletQueryWrapper);
                for (TbUserWalletDetail tbUserWalletDetail : tbUserWalletDetailList) {
                    profit.add(tbUserWalletDetail.getBalance());
                }
                inivate_number += 1;
                able_map.put("profit", profit);
                able_map.put("inivate_number", inivate_number);
            }
        }

    }

    @Override
    public Result<?> updatePhoneById(TbMnUser tbMnUser, String code) {
        if (null == tbMnUser || tbMnUser.getId() == null || tbMnUser.getPhone() == null) {
            return Result.error("参数错误");
        }
        try {
            String phone = tbMnUser.getPhone();
            MobileCodeToken mobileCodeToken = new MobileCodeToken(code, phone);
            mobileCodeToken.isValid();
            redisUtil.del(RedisConstant.getLoginCodeKey(phone));
        } catch (ValidException e) {
            e.printStackTrace();
            return Result.error("验证码错误");
        }
        TbMnUser newTbMnUser = this.getById(tbMnUser.getId());
        newTbMnUser.setPhone(tbMnUser.getPhone());
        this.updateById(newTbMnUser);
        return Result.ok("修改成功");
    }

    @Override
    public Result<?> logout(String user_id) {
        redisUtil.del(JwtUtil.getTokenKey(user_id));
        return Result.ok("退出成功");
    }

    @Override
    public Result<?> readNewGuide(String user_id) {

        TbMnUser tbMnUser = getById(user_id);
        if (tbMnUser.getIsReadGuide() == 1) {
            return Result.error("已经看过引导");
        }
        //设置已读状态。 并增加积分
        TbUserIntegralConfig tbUserIntegralConfig = tbUserIntegralConfigService.getOneByName(TaskNamesConstant.Task_CHA_KAN_YONGHU_YIN_DAO);
        tbMnUser.setIsReadGuide(1);
        BigDecimal rewardValue = tbUserIntegralConfig.getRewardValue();

        TbUserIntegral tbUserIntegral = tbUserIntegralService.getOneByUserId(user_id);
        synchronized (tbUserIntegral) {

            BigDecimal integral = tbUserIntegral.getIntegral();
            BigDecimal newIntegral = integral.add(rewardValue);
            tbUserIntegral.setIntegral(newIntegral);
            tbUserIntegralService.updateById(tbUserIntegral);
            //增加积分明细
            addIntegralDetail(user_id, tbUserIntegral, integral, newIntegral, TaskNamesConstant.Task_CHA_KAN_YONGHU_YIN_DAO);
        }

        return Result.ok("阅读积分成功");
    }

    @Override
    public Result<?> getPersonCenterData(String user_id) {
        Map<String, Object> resultMap = new HashMap<>();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", user_id);
        TbUserSqt tbUserSqt = tbUserSqtService.getOne(queryWrapper);

        TbUserWallet tbUserWallet = tbUserWalletService.getOne(queryWrapper);

        QueryWrapper detailqueryWrapper = new QueryWrapper();
        detailqueryWrapper.eq("user_id", user_id);
        detailqueryWrapper.orderByDesc("create_time");
        List<TbUserWalletDetail> tbUserWalletDetailList = tbUserWalletDetailService.list(detailqueryWrapper);
        if (null != tbUserWalletDetailList && tbUserWalletDetailList.size() > 0) {
            resultMap.put("lately_transact", tbUserWalletDetailList.get(0));
        } else {
            resultMap.put("lately_transact", 0);
        }
        TbMnUser tbMnUser = this.getById(user_id);
        Tb_user_contribution tb_user_contribution = tb_user_contributionService.getOne(detailqueryWrapper);
        resultMap.put("tb_user_contribution", tb_user_contribution);
        resultMap.put("tbUserSqt", tbUserSqt);
        resultMap.put("tbUserWallet", tbUserWallet);
        resultMap.put("tbMnUser", tbMnUser);

        return Result.ok(resultMap);
    }

    public Result<?> checkOldPhone(String user_id, String phone, String code) {
        Map<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            return Result.error("参数错误");
        }
        try {
            MobileCodeToken mobileCodeToken = new MobileCodeToken(code, phone);
            mobileCodeToken.isValid();
            redisUtil.del(RedisConstant.getLoginCodeKey(phone));
        } catch (ValidException e) {
            return Result.error("验证码错误");

        }
        TbMnUser tbMnUser = getById(user_id);
        if (null == tbMnUser) {

            return Result.error("用户不存在");
        }
        if (!tbMnUser.getPhone().equals(phone)) {
            return Result.error("手机号码错误");
        }
        return Result.ok("验证成功");
    }

    public Result<?> updatePhone(String user_id, String newphone, String code) {
        Map<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isEmpty(newphone)) {
            return Result.error("参数错误");
        }

        try {
            MobileCodeToken mobileCodeToken = new MobileCodeToken(code, newphone);
            mobileCodeToken.isValid();
            redisUtil.del(RedisConstant.getLoginCodeKey(newphone));
        } catch (ValidException e) {
            return Result.error("验证码错误");
        }
        TbMnUser tbMnUserByPhone = getUserByPhone(newphone);
        if (null != tbMnUserByPhone) {
            return Result.error("手机号码已经存在");
        }
        TbMnUser tbMnUser = getById(user_id);
        if (null == tbMnUser) {

            return Result.error("用户不存在");
        }
        tbMnUser.setPhone(newphone);
        if (updateById(tbMnUser)) {
            return Result.ok("修改成功");
        }
        return Result.error("修改错误");
    }

    @Override
    public Result<?> updatePushMsgState(String user_id, Integer pushMsgState) {
        TbMnUser tbMnUser = getById(user_id);
        tbMnUser.setPushMsgState(pushMsgState);
        updateById(tbMnUser);
        return Result.ok("设置成功");
    }

    @Override
    public Result<?> updateUserAvater(TbMnUser tbMnUser) {
        if (null == tbMnUser || tbMnUser.getId() == null) {
            return Result.error("参数错误");
        }
        TbMnUser newTbMnUser = this.getById(tbMnUser.getId());
        newTbMnUser.setAvater(tbMnUser.getAvater());
        this.updateById(newTbMnUser);
        return Result.ok("修改成功");
    }

    @Override
    public Result<?> updateUserName(TbMnUser tbMnUser) {
        if (null == tbMnUser || tbMnUser.getId() == null || tbMnUser.getUserName() == null) {
            return Result.error("参数错误");
        }
        TbMnUser newTbMnUser = this.getById(tbMnUser.getId());
        newTbMnUser.setUserName(tbMnUser.getUserName());
        this.updateById(newTbMnUser);
        return Result.ok("修改成功");
    }

    @Override
    public Result<?> bindingWeixin(TbMnUser tbMnUser) {
        if (null == tbMnUser || tbMnUser.getId() == null || tbMnUser.getWeixin() == null) {
            return Result.error("参数错误");
        }
        TbMnUser newTbMnUser = this.getById(tbMnUser.getId());
        newTbMnUser.setWeixin(tbMnUser.getWeixin());
        this.updateById(newTbMnUser);
        return Result.ok("绑定成功");
    }

    @Override
    public Result<?> getMyInvitees(String user_id) {
        TbMnUser tbMnUser = this.getById(user_id);
        if (null == tbMnUser) {
            return Result.error("用户不存在");
        }
        String registerCode = tbMnUser.getRegisterCode();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("invite_code", registerCode);
        TbMnUser new_tbMnUser = this.getOne(queryWrapper);
        Map<String, Object> resultMap = new HashMap<>();
        if (null != new_tbMnUser) {
            resultMap.put("phone", new_tbMnUser.getPhone());
            resultMap.put("phavater", new_tbMnUser.getAvater());
        }

        return Result.ok(resultMap);
    }

    @Override
    public Integer getInviteesNumberByInviteCode(String user_id) {
        TbMnUser tbMnUser = getById(user_id);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("register_code", tbMnUser.getInviteCode());
        List<TbMnUser> tbMnUserList = this.list(queryWrapper);
        int invite_number = 0;
        if (null != tbMnUserList && tbMnUserList.size() > 0) {
            invite_number = tbMnUserList.size();
        }

        return invite_number;
    }

    @Override
    public  Result<?> removeAllData(List<String> asList) {


        for (String id : asList) {
            QueryWrapper queryWrapper = new QueryWrapper();
            synchronized (queryWrapper) {
                queryWrapper.eq("user_id", id);
                tbUserWalletService.remove(queryWrapper);
                tbUserWalletDetailService.remove(queryWrapper);
                tbUserIntegralDetailService.remove(queryWrapper);
                tbUserSqtService.remove(queryWrapper);
                tbUserSqtDetailService.remove(queryWrapper);
                tbUserIntegralConfigDetailService.remove(queryWrapper);
                tbUserCashService.remove(queryWrapper);
                tbUserGameUserShandwService.remove(queryWrapper);
                tbUserLuckdrawDetailService.remove(queryWrapper);
                tbUserGameBuidingService.remove(queryWrapper);
                tbUserIntegralService.remove(queryWrapper);
                QueryWrapper queryWrapper2 = new QueryWrapper();
                queryWrapper2.eq("luck_user_id", id);
                tbUserLuckdrawService.remove(queryWrapper2);
                tb_user_contributionService.remove(queryWrapper);
                tb_user_contribution_detailService.remove(queryWrapper);

                this.removeByUserId(id);
                QueryWrapper adzonequeryWrapper = new QueryWrapper();
                adzonequeryWrapper.eq("account", id);
                TbMnAdzone tbMnAdzone = tbMnAdzoneService.getOne(adzonequeryWrapper);
                if (null != tbMnAdzone) {
                    tbMnAdzone.setAccount("");
                    tbMnAdzone.setState("1");
                    tbMnAdzoneService.update(tbMnAdzone, adzonequeryWrapper);
                }
                PddPromotion pddPromotion = pddPromotionService.getOne(queryWrapper);
                if (null != pddPromotion) {
                    pddPromotion.setStatus(0);
                    pddPromotion.setUserId("");
                    pddPromotionService.updateById(pddPromotion);
                }

                JD_position jd_position = jD_positionService.getOne(queryWrapper);
                if (null != jd_position) {
                    jd_position.setStatus(0);
                    jd_position.setUserId("");
                    pddPromotionService.updateById(pddPromotion);
                }
            }
        }
        this.removeByIds(asList);
        return Result.ok("删除成功");
    }

    @Override
    public Result<?> appRegister(String phone, String inviteCode, String code) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            MobileCodeToken mobileCodeToken = new MobileCodeToken(code, phone);
            mobileCodeToken.isValid();
            redisUtil.del(RedisConstant.getLoginCodeKey(phone));
        } catch (ValidException e) {
            e.printStackTrace();
            return Result.error("验证码错误");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("invite_code", inviteCode);
        TbMnUser tbMnUser_ed = this.baseMapper.selectOne(queryWrapper);
        if (tbMnUser_ed == null) {
            return Result.error("邀请码不存在! ");
        }
        TbMnUser tbMnUser = getUserByPhone(phone);
        if (null == tbMnUser) {
            tbMnUser = getTbMnUser(phone, inviteCode, tbMnUser);
            resultMap.put("state", 1);
            resultMap.put("msg", "用户注册成功");

        } else {
            resultMap.put("state", 0);
            resultMap.put("msg", "用户已经注册，请登陆");
        }
        return Result.ok(resultMap);
    }


    @Override
    public TbMnUser getInviteesUpperFirst(TbMnUser tbMnUser) {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("invite_code", tbMnUser.getRegisterCode());
        TbMnUser tbMnUser_ed = this.baseMapper.selectOne(queryWrapper);

        return tbMnUser_ed;
    }

    @Override
    public void removeByUserId(String id) {

        this.baseMapper.removeByUserId(id);
    }

    private void addIntegralDetail(String user_id, TbUserIntegral tbUserIntegral, BigDecimal integral, BigDecimal newIntegral, String formType) {
        TbUserIntegralDetail tbUserIntegralDetail = new TbUserIntegralDetail();
        tbUserIntegralDetail.setUserId(user_id);
        tbUserIntegralDetail.setBalanceAfter(newIntegral);
        tbUserIntegralDetail.setBalance(integral);
        tbUserIntegralDetail.setState(1);
        tbUserIntegralDetail.setIntegralId(tbUserIntegral.getId());
        tbUserIntegralDetail.setFromType(formType);
        tbUserIntegralDetail.setInOrOut(PayTypeConstant.PAYTYPE_INCOME);
        tbUserIntegralDetailService.save(tbUserIntegralDetail);
    }

    private boolean saveUserWallet(TbMnUser tbMnUser) {
        TbUserWallet tbUserWallet = new TbUserWallet();
        tbUserWallet.setBalance(new BigDecimal(0));
        tbUserWallet.setUserId(tbMnUser.getId());
        tbUserWalletService.save(tbUserWallet);
        return true;
    }

    private boolean saveUserSqt(TbMnUser tbMnUser) {
        TbUserSqt tbUserSqt = new TbUserSqt();
        tbUserSqt.setBalance(new BigDecimal("0"));
        tbUserSqt.setUserId(tbMnUser.getId());
        tbUserSqtService.save(tbUserSqt);
        return true;
    }

    private boolean saveSqtDetail(TbUserSqt tbUserSqt, BigDecimal newBalance) {
        TbUserSqtDetail tbUserSqtDetail = new TbUserSqtDetail();
        tbUserSqtDetail.setPayFrom(PayTypeConstant.PAYFORM_GIVE_SQT);
        tbUserSqtDetail.setPayType(PayTypeConstant.PAYTYPE_INCOME);
        tbUserSqtDetail.setPayNumber(newBalance);
        tbUserSqtDetail.setSqtId(tbUserSqt.getId());
        tbUserSqtDetail.setUserId(tbUserSqt.getUserId());
        if (tbUserSqtDetailService.save(tbUserSqtDetail)) {
            tbUserSqtService.updateById(tbUserSqt);
            return true;
        }
        return false;
    }

    private Result userInfo(TbMnUser tbMnUser) {
        String phone = tbMnUser.getPhone();

        Map<String, Object> data = new HashMap<>(1);
        String token = JwtUtil.signApp(tbMnUser.getId(), phone, sysPassword);
        data.put("token", token);
        data.put("user_id", tbMnUser.getId());
        redisUtil.set(JwtUtil.getTokenKey(tbMnUser.getId()), token, JwtUtil.APP_EXPIRE_TIME);
        return Result.ok(data);
    }


    @Override
    public TbMnUser getUserByPhone(String phone) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone", phone);
        return this.baseMapper.selectOne(queryWrapper);
    }

    @Override
    public Result<?> checkCode(String phone, String code) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            MobileCodeToken mobileCodeToken = new MobileCodeToken(code, phone);
            mobileCodeToken.isValid();
            redisUtil.del(RedisConstant.getLoginCodeKey(phone));
            TbMnUser tbMnUser = getUserByPhone(phone);
            if (null == tbMnUser) {
                resultMap.put("state", 0);
                resultMap.put("msg", "用户不存在");
            } else {
                String token = JwtUtil.signApp(tbMnUser.getId(), phone, sysPassword);
                resultMap.put("state", 1);
                resultMap.put("msg", "登陆成功");
                resultMap.put("token", token);
                resultMap.put("user_id", tbMnUser.getId());
                redisUtil.set(JwtUtil.getTokenKey(tbMnUser.getId()), token, JwtUtil.APP_EXPIRE_TIME);
            }
            return Result.ok(resultMap);
        } catch (ValidException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}
